<template>
    <div class='service'>
        <div class="container">
            <!-- <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" class="search-con">
                <el-form-item label="服务名称" prop="key">
                    <el-input v-model="queryParams.key" placeholder="请输入" clearable size="small" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                    <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form> -->
            <el-row :gutter="10" class="mb8">
                <el-col :span="22">
                    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd()"
                        v-hasPermi="['disabled:service:add']">
                        新增</el-button>
                </el-col>
                <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-table border v-loading="loading" :data="tableList" ref="tableList" v-tableHeight
                :height="tableList.length > 0 ? '900px' : '120px'">
                <el-table-column label="排序" align="center">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.sort" @keyup.native="scope.row.sort=handleNum(scope.row.sort)" @blur="sortTab(scope.row)" clearable size="small" />
                    </template>
                </el-table-column>
                <el-table-column label="服务编号" align="center" prop="id" />
                <el-table-column label="服务封面" align="center" prop="cover_pict">
                    <template slot-scope="scope">
                        <div v-if="scope.row.cover_pict" class="img-list">
                            <el-image style="width: auto; height: 50px;" :src="scope.row.cover_pict"
                                :preview-src-list="[scope.row.cover_pict]">
                            </el-image>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="服务名称" align="center" prop="name" />
                <el-table-column label="服务分类" align="center" prop="cate_name">
                    <!-- <template slot-scope="scope">
                        <span v-if="scope.row.cate_id">
                            {{cateList.find(item=>item.id==scope.row.cate_id).name}}
                        </span>
                    </template> -->
                </el-table-column>
                <el-table-column label="服务价格" align="center" prop="current_price" />
                <el-table-column label="原价" align="center" prop="original_cost" />
                <el-table-column label="服务时长" align="center" prop="service_duration" />
                <el-table-column label="所属第三方" align="center" prop="partner_name">
                    <!-- <template slot-scope="scope">
                        <span v-if="scope.row.partner_id == 0">自营</span>
                        <span v-else>
                            {{ partnerList.find(item => item.id == scope.row.partner_id).partner_name }}
                        </span>
                    </template> -->
                </el-table-column>
                <!-- <el-table-column label="分成" align="center" prop="name" /> -->
                <el-table-column label="是否首页推荐" align="center" prop="is_pick">
                    <template slot-scope="scope">
                        <span>
                            {{ selectDictLabel(statusList1, scope.row.is_pick) }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center" prop="status">
                    <template slot-scope="scope">
                        <span>
                            {{ selectDictLabel(statusList, scope.row.status) }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)"
                            v-hasPermi="['disabled:service:edit']">
                            编辑
                        </el-button>
                        <el-button  size="mini" type="text" @click="handleSetting(scope.row)"
                            v-hasPermi="['disabled:service:stop']">抽成比例
                        </el-button>
                        <el-button v-if="scope.row.is_pick==0" size="mini" type="text" @click="handleSet(scope.row)" v-hasPermi="['user:staff:stop']">设置首页推荐
                        </el-button>
                        <el-button v-if="scope.row.is_pick==1" size="mini" type="text" @click="handleSet(scope.row)" v-hasPermi="['user:staff:stop']">取消首页推荐
                        </el-button>
                        <el-button v-if="scope.row.status == 0" size="mini" type="text" @click="handleAble(scope.row)"
                            v-hasPermi="['disabled:service:start']">停用
                        </el-button>
                        <el-button v-if="scope.row.status == 1" size="mini" type="text" @click="handleAble(scope.row)"
                            v-hasPermi="['disabled:service:start']">启用
                        </el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                            v-hasPermi="['disabled:service:del']">
                            删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="pageCount > 0" :pageCount="pageCount" :page.sync="queryParams.page"
                :limit.sync="queryParams.limit" @pagination="getList" />
        </div>
        <setting v-if="handleShow == 'setting'" :title="title" :handleShow="handleShow" :data="curRow" @close="handleShow = ''" @load="getList" />
        <el-dialog :title="title" visible v-if="handleShow == 'add' || handleShow == 'edit'" @close="close()" width="70%" append-to-body
            :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-loading="formLoading">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="服务分类" prop="cate_id">
                            <el-select style="width:260px;" v-model="form.cate_id" placeholder="请输入选择" size="small">
                                <el-option v-for="dict in cateList" :key="dict.id" :label="dict.name" :value="dict.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="2">
                        <el-form-item label="服务名称" prop="name">
                            <el-input style="width:260px;" v-model="form.name" placeholder="请输入服务名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="服务时长" prop="service_duration">
                            <el-input style="width:260px;" v-model="form.service_duration" placeholder="请输入服务时长">
                                <i slot="suffix"
                                    style="font-style:normal;margin-right: 10px; line-height: 30px; color: #1e1e1e">分钟</i>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="2">
                        <el-form-item label="选择第三方" prop="partner_id" label-width="85px">
                            <el-select v-model="form.partner_id" placeholder="请输入选择" size="small" clearable>
                                <el-option v-for="dict in partnerList" :key="dict.id" :label="dict.partner_name"
                                    :value="dict.id" />
                            </el-select>
                            <!-- <el-input v-model="form.category" placeholder="请输入服务分类" /> -->
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="10" :offset="2">
                        <el-form-item label="会员价格" prop="member_price">
                            <el-input v-model="form.member_price" placeholder="请输入价格" />
                        </el-form-item>
                    </el-col> -->
                    <el-col :span="12">
                        <el-form-item label="现价" prop="current_price">
                            <el-input style="width:260px;" v-model="form.current_price" placeholder="请输入价格" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="10" :offset="2">
                        <el-form-item label="原价" prop="original_cost">
                            <el-input style="width:260px;" v-model="form.original_cost" placeholder="请输入价格" />
                        </el-form-item>
                    </el-col>
                    <!--                     
                    <el-col :span="24">
                        <el-form-item label="服务介绍" prop="content">
                            <el-input v-model="form.content" type="textarea" rows="4" placeholder="请输入服务介绍"></el-input>
                        </el-form-item>
                    </el-col> -->
                    <el-col>
                        <el-form-item label="缩略图" prop="thumbs">
                            <el-upload list-type="picture-card" :file-list="fileList" :before-upload="beforeUpload"
                                :on-change="onchange" :limit="15" :on-exceed="masterFileMax" :class="{ hide: hideUploadBtn }"
                                :action="$uploadUrl"
                                :on-success="(res, file) => handleAvatarSuccess(res, file)">
                                <i slot="default" class="el-icon-plus"></i>
                                <div slot="file" slot-scope="{file}">
                                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                                    <span class="el-upload-list__item-actions">
                                        <span v-if="!disabled" class="el-upload-list__item-delete" style="font-size: small;"
                                            @click="handleFirst(file)">设为首图
                                            <!-- <i class="el-icon-download"></i> -->
                                        </span>
                                        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                            <i class="el-icon-zoom-in"></i>
                                        </span>
                                        <span v-if="!disabled" class="el-upload-list__item-delete"
                                            @click="handleRemove(file)">
                                            <i class="el-icon-delete"></i>
                                        </span>
                                    </span>
                                </div>
                                <div slot="tip" class="el-upload__tip text-error">请上传图片尺寸为750*536的图片</div>
                                <div slot="tip" class="el-upload__tip">最多只能上传15张图片</div>
                                <!-- <img v-if="form.thumb" :src="form.avatar" class="avatar"> -->
                                <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisible" title="图片预览">
                                <img width="100%" :src="dialogImageUrl" alt="">
                            </el-dialog>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="服务介绍" prop="content">
                            <editor v-model="form.content" placeholder="请输入服务介绍" :height="200" />
                            <!-- <template v-else> v-if="edit"
                                    <span v-html="form.content"></span>
                                </template> -->
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="close()">取 消</el-button>
                <el-button type="primary" @click="submit" :disabled="formLoading">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { getServiceLists, setService, setServiceStatus, delService, getServiceInfo, getCateLists, getPartnerLists,setServicePick, setServiceSort } from "@/api/service/service.js"
import { departStatus, yesNo } from "@/api/dictionary"
import setting from "./handle/setting"
import throttle from 'lodash.throttle'
import editor from '@/components/Editor/index'
export default {
    name: 'service',
    props: {

    },
    components: {
        setting,
        editor
    },
    data() {
        return {
            showSearch: true,
            loading: false,
            pageCount: 0,
            total: 0,
            queryParams: {
                page: 1,
                limit: 20,
                key: null,
            },
            tableList: [],
            statusList: departStatus,
            statusList1: yesNo,
            handleShow: "",
            formLoading: false,
            dialogImageUrl: '',
            dialogVisible: false,
            disabled: false,
            hideUploadBtn: false,
            fileList: [],
            picturesList: [],
            limit: '',
            edit: true,
            form: {
                service_id: null,
                name: null,
                rotat_pict: [],
                slider_pict: '',
            },
            rules: {
                name: [{ required: true, message: '请输入服务名称', trigger: 'blur' }],
                cate_id: [{ required: true, message: '请输入服务分类', trigger: 'blur' }],
                member_price: [{ required: true, message: '请输入会员价格', trigger: 'blur' }],
                current_price: [{ required: true, message: '请输入普通价格', trigger: 'blur' }],
                content: [{ required: true, message: '请输入服务介绍', trigger: 'blur' }],
                // thumbs: [{ required: true, message: '请上传缩略图', trigger: 'change' }],
            },
            title: "",
            cateList: [
                { id: 1, name: "助浴" },
                { id: 2, name: "助医" },
                { id: 3, name: "助愉" },
                { id: 4, name: "助健" },
            ],
            partnerList: [],
            editorOption: {
                placeholder: '请输入详情'
            },
        }
    },
    created() {
        this.getList()
        this.getCateLists()
        this.getPartnerLists()
    },
    methods: {
        getList() {
            this.loading = true;
            getServiceLists(this.queryParams).then(res => {
                this.tableList = res.data.lists;
                this.pageCount = res.data.pageCount;
                this.loading = false;
            });
        },
        getCateLists() {
            getCateLists().then(res => {
                this.cateList = res.data;
            });
        },
        getPartnerLists() {
            getPartnerLists().then(res => {
                this.partnerList = res.data;
            });
        },
        handleQuery() {
            this.queryParams.page = 1;
            this.getList();
        },
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        close() {
            this.form = {}
            this.handleShow = ""
        },
        masterFileMax(files, fileList) {
            // this.$message.warning(`请最多上传 ${this.limit} 个文件。`);
            this.$alert('请删除后再上传', '警告', {
                confirmButtonText: '确定',
                type: 'warning'
            });
        },
        beforeUpload(file) {
            return new Promise((resolve, reject) => {
                const isLt2M = file.size / 1024 / 1024 < 1;
                if (!isLt2M) {  // 限制文件大小
                    this.$message.warning(`当前限制文件大小不能大于1M`)
                    return reject(false)
                }
                this.limitFileWH(750, 536, file).then((res) => {
                    file.isFlag = res
                    if (file.isFlag) {
                        return resolve(true)
                    } else {
                        return reject(false)
                    }
                })
            })
        },
        handleAvatarSuccess(res, file) {
            console.log(res.data[0].fileurl, 'res')
            let url = res.data[0].fileurl
            this.fileList.push({
                'url': url
            })
            console.log("上传成功的钩子", this.fileList)
            if (this.fileList.length >= 15) {
                this.hideUploadBtn = true
            }
            // this.picturesList = this.form.rotat_pict
            this.picturesList.push(res.data[0].fileurl)
            console.log(this.picturesList, '图片列表')
            this.form.slider_pict = this.picturesList.length > 0 ? this.picturesList.join("|") : null
            console.log(this.form.slider_pict, "传参")
            this.form.cover_pict = this.picturesList[0]
            // console.log("上传成功的钩子", file);
        },
        onchange(file, fileList) {
            console.log("上传成功", file, fileList);
            if (this.fileList.length >= 15) {
                this.hideUploadBtn = true
            }
            // this.$set(this.form, 'thumbs', fileList)
            this.form.slider_pict = this.picturesList.length > 0 ? this.picturesList.join("|") : null
            console.log(this.form.slider_pict, "传参")
            this.form.cover_pict = this.picturesList[0]
        },
        handleRemove(file, fileList) {
            // this.picturesList = this.form.rotat_pict
            this.picturesList.splice(this.fileList.indexOf(file), 1);
            this.fileList.splice(this.fileList.indexOf(file), 1);
            console.log(this.fileList)
            if (this.fileList.length >= 15) {
                this.hideUploadBtn = true
            } else { this.hideUploadBtn = false }
            console.log(this.picturesList, 'remove')
            this.form.slider_pict = this.picturesList.length > 0 ? this.picturesList.join("|") : null
            console.log(this.form.slider_pict, "传参")
            this.form.cover_pict = this.picturesList[0]
            if (this.picturesList.length = 0) {
                this.form.cover_pict = ''
            }
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        handleDownload(file) {
            console.log(file);
        },
        handleFirst(file, index) {
            console.log(file);
            const objFirst = {
                name: file.name,
                percentage: file.percentage,
                raw: file.raw,
                size: file.size,
                status: file.status,
                uid: file.uid,
                url: file.url
            }
            console.log(this.fileList, '-----')
            this.fileList.unshift(objFirst)
            var index = this.fileList.indexOf(file)
            if (index !== -1) {
                // this.picturesList = this.form.rotat_pict
                this.picturesList.unshift(this.picturesList[index - 1])
                this.picturesList.splice(index, 1)
                this.fileList.splice(index, 1)
            }
            console.log(this.picturesList, 'first')
            this.form.slider_pict = this.picturesList.length > 0 ? this.picturesList.join("|") : null
            console.log(this.form.slider_pict, "传参")
            this.form.cover_pict = this.picturesList[0]
            this.fileList.forEach((e, index) => {
                if (index > 0) {
                    e.index += 1
                }
            });
        },
        // handleAvatarSuccess(res, file) {
        //     this.$set(this.form, 'thumb', res.data[0].fileurl)
        // },
        handleAble(row) {
            let label = row.status == 0 ? '停用' : '启用';
            this.$confirm(`是否将“${row.name}”${label}?`, "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return setServiceStatus({ service_id: row.id });
            }).then(() => {
                this.getList();
                this.msgSuccess(`${label}成功`);
            })
        },
        handleSet(row) {
            let label = row.is_pick == 0 ? '设置为首页推荐' : '取消首页推荐';
            this.$confirm(`是否将“${row.name}”${label}?`, "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return setServicePick({ service_id: row.id });
            }).then(() => {
                this.getList();
                this.msgSuccess(`${label}成功`);
            })
        },
        handleAdd() {
            this.title = '新增';
            this.handleShow = 'add';
            // this.form = {}
            this.fileList = [];
            this.picturesList = [];
        },
        handleEdit(row) {
            this.title = '编辑';
            this.handleShow = 'edit';
            this.fileList = [];
            this.picturesList = [];
            getServiceInfo({ service_id: row.id }).then(res => {
                console.log(res, 'xiangqing')
                this.form = { ...this.form, ...res.data }
                if (res.data.partner_id == 0) {
                    this.form.partner_id = ''
                }
                let zifu = res.data.slider_pict
                this.form.slider = zifu.split("|")
                console.log(this.form.slider, '...')
                if (this.form.slider.length > 0) {
                    for (let i = 0; i < this.form.slider.length; i++) {
                        let url = this.form.slider[i]
                        this.fileList.push({
                            'url': url
                        })
                    }
                    this.picturesList = this.form.slider
                    this.form.slider_pict = this.picturesList.length > 0 ? this.picturesList.join("|") : null
                }
                if (this.form.slider.length >= 15) {
                    this.hideUploadBtn = true
                }
                // this.form.slider_pict = this.picturesList.length > 0 ? this.picturesList.join("|") : null
            })
        },
        sortTab(row) {
            console.log(row, 123)
            setServiceSort({
                sort: row.sort,
                service_id: row.id
            }).then(res => {
                if (res.code == 1) {
                    this.msgSuccess("操作成功");
                    this.getList()
                }
            })
        },
        handleDelete(row) {
            this.$confirm('是否确认删除' + '"' + row.name + '"' + '?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delService({ service_id: row.id });
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            })
        },

        onEditorChange({ editor, html, text }) {
            this.form.content = html;
            // console.log(this.form.content)
        },

        handleSetting(row){
           this.handleShow = "setting"
           this.curRow = row
           this.title = '编辑抽成比例';
        },

        submit: throttle(function () {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.formLoading = true;
                    this.form.service_id = this.form.id
                    this.form.belong_busin_id = this.form.belong_busin_id ? this.form.belong_busin_id : 0
                    // this.form.rotat_pict = this.form.slider_pict
                    setService(this.form).then(res => {
                        this.msgSuccess("操作成功！");
                        this.close()
                        this.formLoading = false;
                        this.getList();
                    }).catch(() => {
                        this.formLoading = false;
                    })
                }
            })
        }, 1000, { trailing: false }),
    }
}
</script>

<style lang='scss' scoped>
// 隐藏上传组件
::v-deep .hide .el-upload--picture-card {
    display: none;
}

// /deep/.avatar-uploader .el-upload {
//     border: 1px dashed #d9d9d9;
//     border-radius: 6px;
//     cursor: pointer;
//     position: relative;
//     overflow: hidden;
//     width: 100px !important;
//     height: 100px !important;
// }

// .avatar-uploader .el-upload:hover {
//     border-color: #409eff;
// }

// .avatar-uploader-icon {
//     font-size: 28px;
//     color: #8c939d;
//     width: 100px !important;
//     height: 100px !important;
//     line-height: 100px !important;
//     /* text-align: center;
//     display: block !important; */
// }

// .avatar {
//     width: 100px;
//     height: 100px;
//     display: block;
// }</style>
